package com.ycsj.goldmedalnewconcept.common.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.just.agentweb.AgentWeb;
import com.mob.MobSDK;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.UnitInfo;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.TestTimeCountUtil;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.sina.weibo.SinaWeibo;

/**
 * 通用-复习-语法检测H5
 */
public class MicroClassroomActivity extends BaseActivity {

    @BindView(R.id.iv_back)
     ImageView iv_back;

    @BindView(R.id.lv_edit)
     ImageView iv_share;

    @BindView(R.id.tv_teacher)
     TextView tv_teacher;

    @BindView(R.id.tv_title)
     TextView tv_title;

//    @BindView(R.id.webview_player)
//     WebView webView;

    @BindView(R.id.tv_content)
     TextView tv_content;

    private String lESSON_ID;

    private String rid;

    //当前页面的单元信息对象和单元号
    private UnitInfo.LessonListBean info;

//    private MyWebChromeClient mMyWebChromeClient;

    private AgentWeb mAgentWeb;


    @BindView(R.id.rl_content)
    RelativeLayout rlContent;

    /**
     * 跳转到当前界面的方法
     *
     * @param info     当前界面的单元信息
     */
    public static void goActivity(Context context, UnitInfo.LessonListBean info, String lessonid) {
        Intent it = new Intent(context, MicroClassroomActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", info);
        it.putExtra("lESSON_ID", lessonid);
        it.putExtras(bundle);
        context.startActivity(it);

    }


    @Override
    protected int getContentLayout() {

        return R.layout.activity_micro_class;
    }

    @Override
    protected void init() {

        //沉浸状态栏
        initStateBar();

        //接收数据
        initIntent();

        //初始化
//        initView();
//        initWebView();
        initAndAddWebView();
        //初始化
        initTitle();

        //设置数据
        initData();
    }

    /**
     * 初始化WebView并添加到视图
     */
    private void initAndAddWebView() {


        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(rlContent, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .createAgentWeb()
                .ready()
                .go(info.getVideo_url());

    }
    /**
     * 设置标题
     */
    private void initTitle() {
        tv_title.setText("微课堂");
        iv_share.setVisibility(View.VISIBLE);
        iv_share.setImageResource(R.drawable.base_share);
    }


    /**
     * 接收数据
     */
    private void initIntent() {
        lESSON_ID = getIntent().getStringExtra("lESSON_ID");
        info = (UnitInfo.LessonListBean) getIntent().getSerializableExtra("data");
    }




    /**
     * 设置数据
     */
    private void initData() {

        //加载视频
//        webView.loadUrl(info.getVideo_url());

        Log.i("test","微课url："+info.getVideo_url());
//        webView.setWebViewClient(new WebViewClient() {
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
//                view.loadUrl(url);
//                return true;
//            }
//        });


        //设置题目
        tv_content.setText(info.getVideo_txt());

        //设置主讲老师
        String substring = lESSON_ID.substring(0, 4);
        if ("3001".equals(substring)) {
            tv_teacher.setText("主讲老师 : Vivi");
        } else if ("3002".equals(substring)) {
            tv_teacher.setText("主讲老师 : Vivi");
        } else if ("3003".equals(substring)) {
            tv_teacher.setText("主讲老师 : Psyche");
        } else if ("3004".equals(substring)) {
            tv_teacher.setText("主讲老师 : Psyche");
        }
    }

//    private void initWebView() {
//
//        //强制打开GPU渲染
//        getWindow().setFlags(
//                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
//                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
//
//
//
//        WebSettings settings = webView.getSettings();
//        settings.setJavaScriptEnabled(true);
//        settings.setJavaScriptCanOpenWindowsAutomatically(true);
//        settings.setPluginState(WebSettings.PluginState.ON);
//        settings.setAllowFileAccess(true);
//        settings.setLoadWithOverviewMode(true);
//        settings.setUseWideViewPort(true);
//        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
//        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
//
//
//        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//
//
//        mMyWebChromeClient = new MyWebChromeClient();
//        webView.setWebChromeClient(mMyWebChromeClient);
//        webView.setWebViewClient(new WebViewClient() {
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                view.loadUrl(url);
//                return true;
//            }
//
//            @Override
//            public void onPageFinished(WebView view, String url) {
//                super.onPageFinished(view, url);
//            }
//        });
//    }


    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_back, R.id.lv_edit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                //返回
                finish();

                break;
            case R.id.lv_edit:
                //分享
                clickShare();
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mAgentWeb.getWebLifeCycle().onPause();
        //停止计时
        TestTimeCountUtil.stopTime(this, rid);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mAgentWeb.getWebLifeCycle().onResume();
        String gradeid = lESSON_ID.substring(0, 4);
        //开始计时  type5微课堂
        TestTimeCountUtil.startTime(this, "5", gradeid, lESSON_ID, new TestTimeCountUtil.onSuccessListener() {
            @Override
            public void onSuccess(String infoRid) {
                rid = infoRid;
            }
        });
    }



    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        mAgentWeb.getWebLifeCycle().onDestroy();
//        webView.setVisibility(View.GONE);
//        webView.removeAllViews();
//        webView.destroy();
//        if (webView != null) {
//            webView = null;
//        }
        System.gc();
    }



    private void clickShare() {

        MobSDK.init(MicroClassroomActivity.this, "12c24ea0b59b0",
                "aae63565fbd69b1acbfcdd0d5ac0b35c");

        OnekeyShare oks = new OnekeyShare();

        // 关闭sso授权
        oks.disableSSOWhenAuthorize();
        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {

            @Override
            public void onShare(Platform platform, ShareParams paramsToShare) {
                if(SinaWeibo.NAME.equals(platform.getName())){
                    paramsToShare.setTitle(getString(R.string.share));
                    paramsToShare.setTitleUrl(info.getVideo_url());
                    String url = info.getVideo_url();
                    if(TextUtils.isEmpty(AccountUtils.getSchoolName(MicroClassroomActivity.this))){
                        paramsToShare.setText( "金牌新概念");
                    }else{
                        paramsToShare.setText(AccountUtils.getSchoolName(MicroClassroomActivity.this));
                    }
                    paramsToShare.setUrl(info.getVideo_url());
                    paramsToShare.setImageUrl("http://139.129.57.83:8080/Appandroid/applogo.png");
                    paramsToShare.setComment("");
                    paramsToShare.setSite(getString(R.string.app_name));
                    paramsToShare.setSiteUrl(info.getVideo_url());

                }else{
                    paramsToShare.setShareType(Platform.SHARE_VIDEO);
                    if(TextUtils.isEmpty(AccountUtils.getSchoolName(MicroClassroomActivity.this))){
                        paramsToShare.setText("金牌新概念");
                    }else{
                        paramsToShare.setText(AccountUtils.getSchoolName(MicroClassroomActivity.this));
                        Log.i("test","学校名称："+AccountUtils.getSchoolName(MicroClassroomActivity.this));
                    }
                    paramsToShare.setTitle(getString(R.string.share));
                    paramsToShare.setTitleUrl(info.getVideo_url());
                    paramsToShare.setText("我正在使用金牌君学习,"+info.getLesson_name()+"重难点视频分享,一起来学习吧,请前往应用宝搜索金牌君下载");
                    paramsToShare.setUrl(info.getVideo_url());
                    paramsToShare.setImageUrl("http://139.129.57.83:8080/Appandroid/applogo.png");
                    paramsToShare.setComment("");
                    paramsToShare.setSite(getString(R.string.app_name));
                    paramsToShare.setSiteUrl(info.getVideo_url());
                }
            }
        });


        // 启动分享GUI
        oks.show(MicroClassroomActivity.this);

    }


    @Override
    public void finish() {
        ViewGroup view = (ViewGroup) getWindow().getDecorView();
        view.removeAllViews();
        super.finish();
    }





//    private class MyWebChromeClient extends WebChromeClient {
//        private View mCustomView;
//        private WebChromeClient.CustomViewCallback mCustomViewCallback;
//        @Override
//        public void onShowCustomView(View view, CustomViewCallback callback) {
//            super.onShowCustomView(view, callback);
//            if (mCustomView != null) {
//                callback.onCustomViewHidden();
//                return;
//            }
//            mCustomView = view;
////            mFrameLayout.addView(mCustomView);
//            mCustomViewCallback = callback;
////            webView.setVisibility(View.GONE);
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//        }
//
//        public void onHideCustomView() {
//            webView.setVisibility(View.VISIBLE);
//            if (mCustomView == null) {
//                return;
//            }
//            mCustomView.setVisibility(View.GONE);
////            mFrameLayout.removeView(mCustomView);
//            mCustomViewCallback.onCustomViewHidden();
//            mCustomView = null;
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//            super.onHideCustomView();
//        }
//    }
//    @Override
//    public void onConfigurationChanged(Configuration config) {
//        super.onConfigurationChanged(config);
//        switch (config.orientation) {
//            case Configuration.ORIENTATION_LANDSCAPE:
//                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
//                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//                break;
//            case Configuration.ORIENTATION_PORTRAIT:
//                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
//                break;
//        }
//    }
}
